#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>

#include "../common/util.hpp"
#include "../common/log.hpp"

namespace rs_runner
{
    using namespace rs_log;
    using namespace rs_util;

    class Runner
    {
    public:
        Runner();
        ~Runner();

        static void SetProRlimit(int _cpu_limit,int _mem_limit)
        {
            //设置cpu时长
            struct rlimit cpu_rlimit;
            cpu_rlimit.rlim_max = RLIM_INFINITY;
            cpu_rlimit.rlim_cur = _cpu_limit;
            setrlimit(RLIMIT_CPU,&cpu_rlimit);

            struct rlimit mem_rlimit;
            mem_rlimit.rlim_max = RLIM_INFINITY;
            mem_rlimit.rlim_cur = _mem_limit*1024;
            setrlimit(RLIMIT_AS,&mem_rlimit);
        }

        static int Run(const std::string &file_name,int cpu_limit,int mem_limit)
        {
            std::string _execute = PathUtil::ExeFile(file_name);
            std::string _stdin = PathUtil::Stdin(file_name);
            std::string _stdout = PathUtil::Stdout(file_name);
            std::string _stderr = PathUtil::Stderr(file_name);

            umask(0);
            int _stdin_fd = open(_stdin.c_str(),O_CREAT|O_WRONLY,0664);
            int _stdout_fd = open(_stdout.c_str(),O_CREAT|O_WRONLY,0664);
            int _stderr_fd = open(_stderr.c_str(),O_CREAT|O_WRONLY,0664);

            if(_stdin_fd < 0||_stdout_fd < 0||_stderr_fd < 0)
            {
                LOG(ERROR) << "没有形成标准文件";
                return -1;
            }

            pid_t pid = fork();
            if(pid < 0)
            {
                LOG(ERROR) << "没有创建子进程";
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                return -2;
            }
            else if(pid == 0)
            {
                dup2(_stdin_fd,0);
                dup2(_stdout_fd,1);
                dup2(_stderr_fd,2);

                SetProRlimit(cpu_limit,mem_limit);
                execl(_execute.c_str(),_execute.c_str(),nullptr);
                exit(1);
            }
            else
            {
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);

                int state = 0;
                pid_t rid = waitpid(pid, &state, 0);
                LOG(INFO) << "运行成功 INFO "<< (state & 0x7F) <<std::endl;
                return (state&0x7F);
            }

        }
    };
}